//
//  BHSportClockDetailViewController.swift
//  BigHealth
//
//  Created by 蔺百好 on 2021/7/16.
//  打卡详情

import UIKit

class BHSportClockDetailViewController: BHBaseViewController {

    lazy var tableView: UITableView = {
        let view = UITableView.buildTableView(style: .grouped)
        view.frame = CGRect(x: 0, y: UIScreen.begainY, width: UIScreen.width, height: UIScreen.showHeight)
        view.delegate = self
        view.dataSource = self
        view.backgroundColor = .white

        return view
    }()
    
    
    // 目标id
    var targetId: String = ""
    fileprivate var model = BHSportSignDetailModel.init()
    fileprivate var recordArray: [BHSportSignRecordModel] = []
    override func viewDidLoad() {
        super.viewDidLoad()

        self.bh_navigationBar.title_label.text = "打卡详情"
        self.bh_navigationBar.rightBtn.isHidden = false
        self.bh_navigationBar.rightBtn.setImage(UIImage.init(named: "bh_sport_clockDetail_nav_share"), for: .normal)
        
        
        self.tableView.regiseterNib(nibName: "BHSportClockDetailTitleCell")
        self.tableView.regiseterNib(nibName: "BHSportClockDetailGoingStateCell")
        self.tableView.regiseterNib(nibName: "BHSportClockTimeCell")
        self.tableView.regiseterNib(nibName: "BHSportClockProgressCell")
        self.tableView.regiseterNib(nibName: "BHSportClockRecordTimeCell")
        self.tableView.regiseterNib(nibName: "BHSportClockDetailHourMinRecordCell")
        self.tableView.regiseterNib(nibName: "BHSportClockTimeLineCell")

        self.view.addSubview(self.tableView)
        
        self.queryTargetDetailService()
        self.querySignRecordService()
    }
    

    override func rightBtnAction() {
        if self.model.status == 0 { // 未开始
            let editeVC = BHSportCreateClockViewController.init()
            editeVC.model = self.model
            self.navigationController?.pushViewController(editeVC, animated: true)
            editeVC.refreshPreviewBlock = { [unowned self] in
                self.queryTargetDetailService()
            }
        }else { // 分享
            
        }
    }

}
extension BHSportClockDetailViewController: UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        if self.model.status == 0 {
            return 2
        }
        return 2+self.recordArray.count
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return 1
        }else if  section == 1 {
            return 2+self.model.planArray.count
        }else {
            let recordModel = self.recordArray[section-2]
            return 2+recordModel.timeSignArray.count
        }
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 {
            return 80
        }else if indexPath.section == 1 {
            if indexPath.row == 0 {
                return 50
            }else if indexPath.row == self.model.planArray.count+1 {
                return 45
            }else {
                return 74
            }
        }else {
            let recordModel = self.recordArray[indexPath.section-2]

            if indexPath.row == 0 {
                return 40
            }else if indexPath.row == recordModel.timeSignArray.count+1 { // 分割线
                return 20
            } else {
                return 34
            }
        }

    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 2 {
            return 45
        }else {
            return CGFloat.leastNormalMagnitude
        }
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return CGFloat.leastNormalMagnitude
    }
  
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    
    }
}

extension BHSportClockDetailViewController: UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if section == 2 {
            let view = UIView.init(frame: CGRect(x: 0, y: 0, width: UIScreen.width, height: 45))
            view.backgroundColor = .white
            
            let  label = UILabel.init(frame: CGRect(x: 16, y: 10, width: UIScreen.width-32, height: 35))
            label.text = "打卡记录"
            label.textColor = .color_333333
            label.font = .systemFont(ofSize: 14, weight: .medium)
            view.addSubview(label)
            
            let  space = UILabel.init(frame: CGRect(x: 0, y: 0, width: UIScreen.width, height: 10))
            space.backgroundColor = .color_f8f8f8
            view.addSubview(space)
            
            return view
        }else {
            return nil
        }
    }
  
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "BHSportClockDetailTitleCell", for: indexPath) as! BHSportClockDetailTitleCell
            if self.model.targetId.isEmpty == false {
                cell.title_label.text = self.model.target
                cell.plan_label.text = self.model.plan
            }
            return cell
        }else if indexPath.section == 1 {
            return self.cellForToday(indexPath: indexPath)
        }
        else {
            return self.cellForDayTime(indexPath: indexPath)
        }
        
    }
}

extension BHSportClockDetailViewController {
    func cellForToday(indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "BHSportClockDetailGoingStateCell", for: indexPath) as! BHSportClockDetailGoingStateCell
            if self.model.targetId.isEmpty == false {
                cell.state_label.text = model.statusText
                cell.keep_time_label.text = "\(self.model.startTime)至\(self.model.endTime)"
            }
            return cell
        }else if indexPath.row == self.model.planArray.count+1 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "BHSportClockProgressCell", for: indexPath) as! BHSportClockProgressCell
            if self.model.targetId.isEmpty == false {
                cell.model = self.model
            }
            return cell
        }else {
            let cell = tableView.dequeueReusableCell(withIdentifier: "BHSportClockTimeCell", for: indexPath) as! BHSportClockTimeCell
            if self.model.planArray.count != 0 {
                let planModel = self.model.planArray[indexPath.row-1]
                
                cell.model = planModel
                if self.model.status == 0 { // 未开始单独处理
                    cell.clock_btn.isHidden = self.model.status == 0
                    cell.back_view.backgroundColor = .color_f8f8f8
                }
            
                cell.clock_btn.addBtnAction(action: {[weak self] (_) in
                    if planModel.clockStatus == 0 {
                        self?.signSport(planModel: planModel)
                    }
                    
                }, for: .touchUpInside)
            }
            return cell
        }
    }
}

extension BHSportClockDetailViewController {
    func cellForDayTime(indexPath: IndexPath) -> UITableViewCell {
        let recordModel = self.recordArray[indexPath.section-2]

        if indexPath.row == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "BHSportClockRecordTimeCell", for: indexPath) as! BHSportClockRecordTimeCell
            cell.date_label.text = recordModel.day
            return cell
        }else if indexPath.row == recordModel.timeSignArray.count+1 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "BHSportClockTimeLineCell", for: indexPath) as! BHSportClockTimeLineCell
            return cell
        }
        
        else {
            let cell = tableView.dequeueReusableCell(withIdentifier: "BHSportClockDetailHourMinRecordCell", for: indexPath) as! BHSportClockDetailHourMinRecordCell
            let timeModel = recordModel.timeSignArray[indexPath.row-1]
            cell.time_label.text = timeModel.clockTime
            cell.state_label.text = timeModel.dayClockFlag == 1 ? "已打卡":"缺卡"
            return cell
        }
    }
}
extension BHSportClockDetailViewController {
    func queryTargetDetailService() {
        SVProgressHUD.show()
        let manager = BHHTTPClient.init()
        manager.get(url: String.sport_target_detail_url, paramters: ["id":self.targetId]) {[unowned self] (success, errorMsg, responseDic) in
            SVProgressHUD.dismiss()
            if success == true {
                let result = BHJsonTool.decodeDicFromDic(dic: responseDic, key: "result")
                self.model.parseDic(result)
                self.tableView.reloadData()
                
                self.bh_navigationBar.rightBtn.isHidden = false
                if self.model.status == 0 { // 未开始
                    self.bh_navigationBar.rightBtn.setTitle("编辑", for: .normal)
                    self.bh_navigationBar.rightBtn.setImage(UIImage.init(named: ""), for: .normal)
                }else {
                    self.bh_navigationBar.rightBtn.setTitle("", for: .normal)
                    self.bh_navigationBar.rightBtn.setImage(UIImage.init(named: "bh_sport_clockDetail_nav_share"), for: .normal)
                }
            }else {
                BHToast.toast(text: errorMsg)
            }
        }
    }
}

// MARK: 获取打卡记录
extension BHSportClockDetailViewController {
    func querySignRecordService()  {
        BHSportServiceManager.sportSignRecordListService(targetId: self.targetId) {[unowned self] (success, errorMsg, array) in
            if success == true {
                if self.recordArray.count != 0 {
                    self.recordArray.removeAll()
                }
                self.recordArray.append(contentsOf: array)
                
                self.tableView.reloadData()
            }else {
                BHToast.toast(text: errorMsg)
            }
        }
    }
}

// MARK: 打卡
extension BHSportClockDetailViewController {
    func signSport(planModel: BHSportPlanModel) {
        SVProgressHUD.show()
        BHSportServiceManager.sportSignService(targetId: self.targetId, planId: planModel.planId) {[unowned self] (success, errorMsg) in
            SVProgressHUD.dismiss()
            if success == true {
                BHToast.toast(text: "打卡成功")
                planModel.clockStatus = 1
                self.tableView.reloadData()
            }else {
                BHToast.toast(text: errorMsg)
            }
        }
    }
}
